<template>
    <div>
        <el-form :model="userinfo" ref="userinfo" :rules="rules" label-width="100px" class="demo-dynamic">
            <el-form-item label="用户名" prop="username">
                <el-input type="text" v-model="userinfo.username" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="pass">
                <el-input type="password" v-model="userinfo.pass" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm('userinfo')">登录</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import axios from 'axios';
export default {
    data(){
        return {
            userinfo: {
                pass:'',     //密码
                username:''  //用户名
            },
            rules: {
                username:[
                    {required: true, message: '请输入用户名', trigger: 'blur' }
                ],
                pass: [
                    { required: true, message: '请输入密码', trigger: 'blur' }
                ]
            }
        }
    },
    methods:{
        //提交表单  登录
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let {username,pass} = this.userinfo;
                    axios.post('/api/login',{username,password:pass}).then(res => {
                        if(res.data.code === 1){
                            localStorage.setItem('token',res.data.token);
                            localStorage.setItem('username',this.userinfo.username);
                            this.$message({
                                message: '恭喜你，登录成功',
                                type: 'success',
                                duration:1000,
                                onClose:()=>{
                                    this.$router.push('/main');
                                }
                            });
                        }else{
                            this.$message.error('登录失败');
                        }
                    })
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        }
    }
}
</script>